package com.imooc.example.order.query;

import com.imooc.example.order.event.StudentFinishedEvent;
import com.imooc.example.order.event.saga.StudentCreatedEvent;
import com.imooc.example.order.event.StudentFailedEvent;
import lombok.extern.slf4j.Slf4j;
import org.axonframework.eventhandling.EventHandler;
import org.axonframework.eventsourcing.EventSourcingHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class StudentProjector {

    @Autowired
    private StudentBeanJpa studentBeanJpa;

    @EventHandler
    public void onCreate(StudentCreatedEvent event) {

        StudentBean studentBean = StudentBean.builder()
                .id(event.getStudentId())
                .name(event.getName()).build();

        studentBeanJpa.save(studentBean);
        log.info("StudentCreatedEvent 保存 {}", studentBean);
    }

    @EventSourcingHandler
    public void onFinish(StudentFinishedEvent event) {
        StudentBean studentBean = StudentBean.builder()
                .id(event.getStudentId())
                .name(event.getName())
                .age(event.getAge()).build();
        studentBeanJpa.saveAndFlush(studentBean);
        log.info("更新年龄 = {}", studentBean);
    }

    @EventSourcingHandler
    public void onFail(StudentFailedEvent event) {
        StudentBean studentBean = studentBeanJpa.findOne(event.getStudentId());
        studentBean.setReason(event.getReason());
        log.info("询问失败: 原因 = {}", event.getReason());
        studentBeanJpa.saveAndFlush(studentBean);
    }

}
